<%
/**
 * Copyright (c) Yi Yuen Kok Dexter 100089812 UNISA
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/security" prefix="liferay-security" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://liferay.com/tld/util" prefix="liferay-util" %>

<%@ page import="com.liferay.mail.model.Account" %>
<%@ page import="com.liferay.mail.model.Attachment" %>
<%@ page import="com.liferay.mail.model.Folder" %>
<%@ page import="com.liferay.mail.model.Message" %>
<%@ page import="com.liferay.mail.model.MessageDisplay" %>
<%@ page import="com.liferay.mail.model.MessagesDisplay" %>
<%@ page import="com.liferay.mail.service.AccountLocalServiceUtil" %>
<%@ page import="com.liferay.mail.service.AttachmentLocalServiceUtil" %>
<%@ page import="com.liferay.mail.service.FolderLocalServiceUtil" %>
<%@ page import="com.liferay.mail.service.MessageLocalServiceUtil" %>
<%@ page import="com.liferay.mail.util.MailConstants" %>
<%@ page import="com.liferay.mail.util.MailManager" %>
<%@ page import="com.liferay.mail.util.PortletPropsValues" %>
<%@ page import="com.liferay.portal.kernel.json.JSONArray" %>
<%@ page import="com.liferay.portal.kernel.json.JSONFactoryUtil" %>
<%@ page import="com.liferay.portal.kernel.json.JSONObject" %>
<%@ page import="com.liferay.portal.kernel.language.LanguageUtil" %>
<%@ page import="com.liferay.portal.kernel.portlet.LiferayWindowState" %>
<%@ page import="com.liferay.portal.kernel.util.FastDateFormatFactoryUtil" %>
<%@ page import="com.liferay.portal.kernel.util.GetterUtil" %>
<%@ page import="com.liferay.portal.kernel.util.HtmlUtil" %>
<%@ page import="com.liferay.portal.kernel.util.ParamUtil" %>
<%@ page import="com.liferay.portal.kernel.util.StringBundler" %>
<%@ page import="com.liferay.portal.kernel.util.StringPool" %>
<%@ page import="com.liferay.portal.kernel.util.StringUtil" %>
<%@ page import="com.liferay.portal.kernel.util.UnicodeFormatter" %>
<%@ page import="com.liferay.portal.kernel.util.Validator" %>
<%@ page import="com.liferay.portal.util.PortalUtil" %>
<%@ page import="com.liferay.util.portlet.PortletProps" %>
<%@ page import="com.liferay.OTP.*" %>

<%
	boolean encryptedOtp = false; 
	boolean foundElement = false;
	boolean findKey = false;
	boolean findCt= false;
	String unencryptedMessageStr = "-----THIS IS AN UNENCRPYTED MESSAGE--------------<br />";
	String encryptedMessageStr = "-----THIS IS AN ENCRPYTED MESSAGE--------------<br />";
	String opHeaderStr = "</OTPHEADER>";
	String opFooterStr = "OTPHEADER_END";
	String ciperIDTag = "</CIPHER_ID>";
	String keyIDTag = "</OTP_KEY_ID>";
	int headerIndexStart;
	int headerIndexEnd;
	String messageTyper = ParamUtil.getString(request, "messageType");
	
	System.out.println("Message_type:"+ messageTyper);
	String messageStr = "";
	
	if (messageTyper==""){
		messageStr = message.getBody();
	} 
	else if (messageTyper.equals("edit")) {
		Message messageEdit = MessageLocalServiceUtil.getMessage(messageId);
		messageStr = messageEdit.getBody();
	}
	else if (!messageTyper.equals("new")){
		long replyMessageIdr = ParamUtil.getLong(request, "replyMessageId");
		Message replyMessager = MessageLocalServiceUtil.getMessage(replyMessageIdr);
		messageStr = replyMessager.getBody();
	
	}
	if (messageStr.contains(opHeaderStr)   &&   messageTyper.equals("new")==false )   {
		
		encryptedOtp = true;

		System.out.println("Encryption Detected in this email");
		
		if(messageStr.contains(ciperIDTag)){
			OTPCipherText ct = OTPServiceUtil.extractOTPCipherText(messageStr);
			findKey = true;
			System.out.println("CT detected in message CT_ID: " + ct.getID());
		} else if(messageStr.contains(keyIDTag)){
			OTPkey k = OTPServiceUtil.extractOTPKey(messageStr);
			findCt = true;
			System.out.println("KEY detected in message KEY_ID:" + k.getID());
		} else {
			System.out.println("Error: Enc detected, but message is not a key/ct.");
		}
		

		List <Account> mailAccounts = mailManager.getAccounts();	
		
		
		
		for (Account mailAccount : mailAccounts){
			if (mailAccount.getAccountId()!= accountId){
				
				//System.out.println(mailAccount.getAddress());
				List<Folder> folders = mailManager.getFolders(mailAccount.getAccountId(), true, true);
	
			for (Folder folder: folders){
				
				
				if (folder.getFolderId() == mailAccount.getInboxFolderId()){	
				//System.out.println(folder.getDisplayName());
				MessagesDisplay messagesDisplayTest = mailManager.getMessagesDisplay(folder.getFolderId(), 1, 9000, "sentDate", "desc", "OTP");
				List<Message> messages = messagesDisplayTest.getMessages();
				
				for(Message messageTest : messages){
					
					if (findKey){
						if(messageTest.getBody().contains(keyIDTag)){
							OTPkey k = OTPServiceUtil.extractOTPKey(messageTest.getBody());
							OTPCipherText ct = OTPServiceUtil.extractOTPCipherText(messageStr);
							
							System.out.println("KEY/CT: " + k.getID()+ct.getID());
							if(k.getID().equals(ct.getID())){
								foundElement = true;	
								System.out.println("Found a matching KEY for ID: "+ k.getID()+ ". Performing Decryption.");
								messageStr = OTPServiceUtil.OTPDecrypt(k,ct);
								System.out.println("Decryption Done.");
							}
						}					
					} else if(findCt){
						if(messageTest.getBody().contains(ciperIDTag)){
							OTPkey k = OTPServiceUtil.extractOTPKey(messageStr);
							OTPCipherText ct = OTPServiceUtil.extractOTPCipherText(messageTest.getBody());
							System.out.println("KEY/CT: " + k.getID()+ct.getID());
							
							if(ct.getID().equals(k.getID())){
								foundElement = true;	
								System.out.println("Found a matching CT for ID:  "+ ct.getID()+ ". Performing Decryption.");
								messageStr = OTPServiceUtil.OTPDecrypt(k,ct);
								System.out.println("Decryption Done.");
							}												

						}
					
					}
					
					
					if(foundElement)break;
				}
				if(foundElement)break;
				
				}	
			}		
			}
		}
		


		
		
		
	}
	
	if (findKey ==true && foundElement==false ){
		messageStr = "Unable to Decrypt: OTP Key not found.";
	} else	if (findCt ==true && foundElement==false ){
		messageStr = "Unable to Decrypt: CT Key not found.";
	}
	
%>